<?php

namespace App\Http\Controllers;

use App\Utils\FunctionUtil;
use Illuminate\Routing\Controller;

/**
 * Api基础控制器
 */
abstract class ApiBaseController extends Controller
{
  protected array $result = [
    "code" => 0,
    "message" => "操作成功",
    "data" => [],
  ];

  /**
   * 类名调用
   * @return array
   */
  public function __invoke(): array
  {
    //参数检测
    $this->check();
    if ($this->result["code"] !== 0) {
      return $this->result;
    }
    //主体逻辑
    $this->service();
    //返回格式
    if (!empty($this->result['data'])) {
      !is_string($this->result['data']) && $this->result['data'] = FunctionUtil::formatResult($this->result['data']);
    }

    // response($this->result, 200);
    return $this->result;
  }

  /**
   * 参数检测
   * @return void
   */
  protected abstract function check(): void;

  /**
   * 主体逻辑
   * @return void
   */
  protected abstract function service(): void;


  /**
   * 查询构造器
   * @param $queryContruct
   * @param array $searchMap
   * @return void
   */
  protected function querySearchConstructor(&$queryContruct, array $searchMap): void
  {
    foreach ($searchMap as $requestKey => $searchRule) {
      $requestKeyVal = request($requestKey);
      if (isset($requestKeyVal) && (!empty($requestKeyVal) || $requestKeyVal == "0")) {
        switch ($searchRule[1]) {
          case "=":
            $queryContruct->where($searchRule[0], $requestKeyVal);
            break;
          case ">":
            $queryContruct->where($searchRule[0], ">", $requestKeyVal);
            break;
          case "<":
            $queryContruct->where($searchRule[0], "<", $requestKeyVal);
            break;
          case "in":
            $queryContruct->whereIn($searchRule[0], $requestKeyVal);
            break;
          case "rlike":
            $queryContruct->where($searchRule[0], 'like', $requestKeyVal . '%');
            break;
          case "like":
            $queryContruct->where($searchRule[0], 'like', '%' . $requestKeyVal . '%');
            break;
          case "raw":
            $num = empty($searchRule[2]) ? 1 : intval($searchRule[2]);
            $rawArr = [];
            for ($i = 0; $i < $num; $i++) {
              $rawArr[] = $requestKeyVal;
            }
            $queryContruct->whereRaw($searchRule[0], $rawArr);
            break;
        }
      }
    }
  }
}
